import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { createApp } from "vue";
import router from "@/router/index";

const baseURL = import.meta.env.VITE_BASE_URL;

//1. 创建axios对象
const service = axios.create({
  baseURL: baseURL,
  timeout: 5000
});

//2. 请求拦截器
service.interceptors.request.use(
  (config) => {
    config.headers["X-CLIENT"] = "CLIENT_PC";
    // config.headers["Authorization"] =
    //   "Bearer " +
    //   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3QgVXNlciIsImlhdCI6MTcyMjQwMDAwMCwiZXhwIjoxNzIyNDg2NDAwfQ.SFlLuPq_lE7qWQqY8uoP0S69V4oJHRvD7kGx6s0y2hc";
    if (!config.url.includes("login")) {
      let xtoken = sessionStorage.getItem("token") ? sessionStorage.getItem("token") : "";
      if (xtoken) {
        config.headers["X-TOKEN"] = xtoken;
        // xtoken == "kGHkUXygjQQw7kBfXO6e0OWv"
        //   ? (config.headers["token"] = xtoken)
        //   : (config.headers["X-TOKEN"] = xtoken);
      }
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

//3. 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { code, msg } = response.data;
    if (code == 1000) {
      return response.data;
    } else {
      ElMessage(msg);
      return response.data;
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

const request = (url, method, data) => {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: method,
      data: data
    })
      .then((res) => resolve(res))
      .catch((err) => reject(err));
  });
};

export { service, request };
